package com.example.mytest.file;

import java.io.File;

public class RenameFiles {

    static final String path = "D:\\Tools\\360jiagubao_windows_64\\jiagu\\output\\20211117";
    static final String dir = "D:\\Tools\\360jiagubao_windows_64\\jiagu\\output\\5.2.2.7（149）";
    static final String splitStr = "5227_";

    public static void main(String[] args) {
        listFiles();
    }

    private static void listFiles(){

        File f = new File(path);
        if (!f.exists()) {
            System.out.println(path + " not exists");
            return;
        }

        File fa[] = f.listFiles();
        for (File fs : fa) {
            if (fs.isFile()) {
                System.out.println(fs.getName());
                reName(fs);
            }
        }
    }

    private static void reName(File file){
        String name = file.getName();
        String[] names = name.split(splitStr);
        StringBuilder newName = new StringBuilder();
        if (names.length>1){
            newName.append(names[0])
            .append(splitStr)
            ;
            String[] delStr = names[1].split("_");
            for (int i=1;i<delStr.length;++i){
                if (i!=1){
                    newName.append("_");
                }
                newName.append(delStr[i]);
            }
        }
        System.out.println(newName);
        File newFile = new File(dir+File.separator+newName.toString());
        if (!newFile.getParentFile().exists()){
            newFile.getParentFile().mkdirs();
        }
        boolean isRename = file.renameTo(newFile);
        if (!isRename){
            System.out.println("名称修改失败！");
        }
    }
}
